package org.example.springtrans.controller;

import lombok.extern.slf4j.Slf4j;
import org.example.springtrans.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;


@Slf4j
@RequestMapping("/trans")
@RestController
public class TransactionalController {
    @Autowired
    private UserService userService;

    @Transactional
    @RequestMapping("/registry")
    public String registry(String name, String password) {
        // 用户注册
        userService.registryUser(name, password);
        log.info("用户数据插入成功");
        try {
            int a = 10 /0 ;
        }catch (Exception e) {
           // throw e;
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return "注册成功";
    }
    @Transactional(rollbackFor = Exception.class)
    @RequestMapping("/r2")
    public String r2(String name, String password) throws IOException {
        userService.registryUser(name, password);
        log.info("用户数据插入成功");
        if (true) {
            throw new IOException();
        }
        return "r2";
    }

    @Transactional(isolation = Isolation.READ_COMMITTED)
    @RequestMapping("/r3")
    public String r3(String name, String password) throws IOException {

        return "r3";
    }
}
